'use strict';

Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends2 = require('babel-runtime/helpers/extends');

var _extends3 = _interopRequireDefault(_extends2);

var _objectWithoutProperties2 = require('babel-runtime/helpers/objectWithoutProperties');

var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2);

var _slicedToArray2 = require('babel-runtime/helpers/slicedToArray');

var _slicedToArray3 = _interopRequireDefault(_slicedToArray2);

var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _createClass2 = require('babel-runtime/helpers/createClass');

var _createClass3 = _interopRequireDefault(_createClass2);

var _inherits2 = require('babel-runtime/helpers/inherits');

var _inherits3 = _interopRequireDefault(_inherits2);

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _propTypes = require('prop-types');

var _propTypes2 = _interopRequireDefault(_propTypes);

var _reactBeautifulDnd = require('react-beautiful-dnd');

var _popover = require('antd/lib/popover');

var _popover2 = _interopRequireDefault(_popover);

var _row = require('antd/lib/row');

var _row2 = _interopRequireDefault(_row);

var _col = require('antd/lib/col');

var _col2 = _interopRequireDefault(_col);

var _reactLifecyclesCompat = require('react-lifecycles-compat');

var _MenuOutlined = require('@ant-design/icons/MenuOutlined');

var _MenuOutlined2 = _interopRequireDefault(_MenuOutlined);

var _DeleteOutlined = require('@ant-design/icons/DeleteOutlined');

var _DeleteOutlined2 = _interopRequireDefault(_DeleteOutlined);

var _PlusOutlined = require('@ant-design/icons/PlusOutlined');

var _PlusOutlined2 = _interopRequireDefault(_PlusOutlined);

var _utils = require('../../utils');

var _BackGroundPop = require('./BackGroundPop');

var _BackGroundPop2 = _interopRequireDefault(_BackGroundPop);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }

var BackGroundImage = function (_React$Component) {
    (0, _inherits3['default'])(BackGroundImage, _React$Component);
    (0, _createClass3['default'])(BackGroundImage, null, [{
        key: 'getDerivedStateFromProps',
        value: function getDerivedStateFromProps(props, _ref) {
            var prevProps = _ref.prevProps,
                $self = _ref.$self;

            var nextState = {
                prevProps: props
            };
            if (prevProps) {
                if (props.editorElem !== prevProps.editorElem) {
                    $self.keys = [];
                }
            }
            return nextState;
        }
    }]);

    function BackGroundImage(props) {
        (0, _classCallCheck3['default'])(this, BackGroundImage);

        var _this = (0, _possibleConstructorReturn3['default'])(this, (BackGroundImage.__proto__ || Object.getPrototypeOf(BackGroundImage)).call(this, props));

        _initialiseProps.call(_this);

        _this.state = {
            $self: _this // eslint-disable-line
        };
        return _this;
    }

    (0, _createClass3['default'])(BackGroundImage, [{
        key: 'componentWillUnmount',
        value: function componentWillUnmount() {
            this.keys = [];
        }

        // for 外部主动发起修改

        // for 外部主动发起修改

    }, {
        key: 'render',
        value: function render() {
            var _props = this.props,
                locale = _props.locale,
                className = _props.className;

            var childToRender = this.getChildrenToRender();
            return _react2['default'].createElement(
                'div',
                { className: className + '-wrapper' },
                childToRender,
                _react2['default'].createElement(
                    _row2['default'],
                    { gutter: 8 },
                    _react2['default'].createElement(
                        _col2['default'],
                        { span: 24 },
                        _react2['default'].createElement(
                            'a',
                            { className: 'add-button', onClick: this.onAdd },
                            _react2['default'].createElement(_PlusOutlined2['default'], null),
                            ' ',
                            locale.add
                        )
                    )
                )
            );
        }
    }]);
    return BackGroundImage;
}(_react2['default'].Component);

BackGroundImage.propTypes = {
    className: _propTypes2['default'].string,
    locale: _propTypes2['default'].object,
    value: _propTypes2['default'].any,
    onChange: _propTypes2['default'].func,
    editorElem: _propTypes2['default'].any,
    imageSelect: _propTypes2['default'].bool,
    onImageSelectClick: _propTypes2['default'].func
};
BackGroundImage.defaultProps = {
    className: 'editor-bg-image',
    imageSelect: false,
    onImageSelectClick: function onImageSelectClick() {}
};

var _initialiseProps = function _initialiseProps() {
    var _this2 = this;

    this.onDragEnd = function (result) {
        var source = result.source,
            destination = result.destination;

        if (destination && source.index !== destination.index) {
            var value = _this2.props.value;

            Object.keys(value).forEach(function (key) {
                var item = value[key];

                var _item$splice = item.splice(source.index, 1),
                    _item$splice2 = (0, _slicedToArray3['default'])(_item$splice, 1),
                    removed = _item$splice2[0];

                item.splice(destination.index, 0, removed);
                value[key] = item;
            });
            _this2.props.onChange(value);
        }
    };

    this.onDeleteChild = function (i) {
        var value = _this2.props.value;

        Object.keys(value).forEach(function (key) {
            var item = value[key];
            item.splice(i, 1);
            value[key] = item;
        });
        _this2.props.onChange(value);
    };

    this.onAdd = function () {
        var defaultData = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
        var value = _this2.props.value;

        Object.keys(value).forEach(function (key) {
            if (defaultData && defaultData[key]) {
                value[key].unshift(defaultData[key]);
            } else {
                value[key].unshift(_utils.defaultBgImageValue[key]);
            }
        });
        _this2.keys.unshift(_this2.getRand());
        _this2.addNum = 0;
        _this2.props.onChange(value);
    };

    this.getValue = function () {
        return _this2.props.value;
    };

    this.onEdit = function (value) {
        _this2.props.onChange(value);
    };

    this.getRand = function () {
        return (Math.random() + Date.now()).toString(16).replace('.', Math.random().toFixed(6).replace('0.', ''));
    };

    this.getChildrenToRender = function () {
        var _props2 = _this2.props,
            className = _props2.className,
            data = _props2.value,
            props = (0, _objectWithoutProperties3['default'])(_props2, ['className', 'value']);

        var children = data.image.filter(function (c) {
            return c;
        }).map(function (url, i) {
            var type = (0, _utils.getBgImageType)(url);
            var imageNameSplit = (0, _utils.getBgImageUrl)(url).split('/');
            var name = type === 'img' ? imageNameSplit[imageNameSplit.length - 1] : type + '-gradient';
            _this2.keys[i] = _this2.keys[i] || _this2.getRand();
            var defaultVisible = void 0;
            if (i === _this2.addNum) {
                defaultVisible = true;
                _this2.addNum = NaN;
            }
            return _react2['default'].createElement(
                _reactBeautifulDnd.Draggable,
                { key: _this2.keys[i], index: i, draggableId: _this2.keys[i] },
                function (provided) {
                    return _react2['default'].createElement(
                        _popover2['default'],
                        {
                            content: _react2['default'].createElement(_BackGroundPop2['default'], (0, _extends3['default'])({}, props, {
                                value: data,
                                num: i
                            })),
                            defaultVisible: defaultVisible,
                            trigger: 'click',
                            overlayClassName: 'editor-list-popover',
                            destroyTooltipOnHide: true // svg defs 阴藏后不会显示渐变了。
                        },
                        _react2['default'].createElement(
                            'div',
                            (0, _extends3['default'])({
                                ref: provided.innerRef
                            }, provided.draggableProps, {
                                className: className + '-list'
                            }),
                            _react2['default'].createElement(_MenuOutlined2['default'], (0, _extends3['default'])({
                                className: className + '-list-bar'
                            }, provided.dragHandleProps)),
                            _react2['default'].createElement('div', { style: { backgroundImage: url }, className: className + '-list-preview' }),
                            _react2['default'].createElement(
                                'a',
                                { className: className + '-list-name' },
                                name
                            ),
                            _react2['default'].createElement(
                                'div',
                                {
                                    className: className + '-list-delete',
                                    onClick: function onClick() {
                                        _this2.onDeleteChild(i);
                                    }
                                },
                                _react2['default'].createElement(_DeleteOutlined2['default'], null)
                            )
                        )
                    );
                }
            );
        });
        return _react2['default'].createElement(
            _row2['default'],
            { gutter: 8 },
            _react2['default'].createElement(
                _col2['default'],
                null,
                _react2['default'].createElement(
                    _reactBeautifulDnd.DragDropContext,
                    {
                        onDragStart: _this2.onDragStart,
                        onDragEnd: _this2.onDragEnd
                    },
                    _react2['default'].createElement(
                        _reactBeautifulDnd.Droppable,
                        { key: 'bgImage', droppableId: 'bgImage' },
                        function (provided) {
                            return _react2['default'].createElement(
                                'div',
                                {
                                    ref: provided.innerRef,
                                    className: className + '-droppable'
                                },
                                children,
                                provided.placeholder
                            );
                        }
                    )
                )
            )
        );
    };

    this.keys = [];
};

exports['default'] = (0, _reactLifecyclesCompat.polyfill)(BackGroundImage);
module.exports = exports['default'];